﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GameSchool.Models;
using GameSchool.ViewModels;
using System.Diagnostics;

namespace GameSchool.Controllers
{
    public class AnnouncementController : Controller
    {
		//Tilkynningar
		AnnouncementRepository repository = new AnnouncementRepository();

		GameRepository gameRepository = new GameRepository();
		

        public ActionResult Index()
        {
			return RedirectToAction("Announcements");
        }

		//Þetta er "Tilkynningar" hlekkur á forsíðu umsjónarmanns
		//Aðeins hann á að geta séð allar tilkynningar kerfisins
		public ActionResult Announcements()
		{
			if (User.IsInRole("Admin"))
			{
				var items = from n in repository.Announcements()
							orderby n.Date descending
							select n;

				return View(items);
			}
			else
			{
				//Annars hefur notandi ekki réttindi og er hent á viðeigandi síðu
				return RedirectToAction("Index", "Home");
			}
		}


		//Aðeins kennari og/eða umsjónarmaður á að geta búið til tilkynningu
		[HttpGet]
		public ActionResult createAnnouncement(int? id)
		{
			if (User.IsInRole("Admin")||User.IsInRole("Teacher"))
			{
				if (id.HasValue)
				{
					ViewData["currLevel"] = id;
					return View(new Announcement());
				}
				else
				{
					ViewBag.Message = "Villa kom upp, reynum við ekki bara aftur ?";
					return RedirectToAction("Index", "Home");
				}
			}
			else
			{
				return RedirectToAction("Index", "Home");
			}
		}


		//Aðeins umsjónarmaður og kennari geta búið til tilkynningu
		[HttpPost]
		[Authorize(Roles = "Admin,Teacher")]
		public ActionResult createAnnouncement(FormCollection formData)
		{
			if (User.IsInRole("Admin")||User.IsInRole("Teacher"))
			{
				Announcement newAnnouncement = new Announcement();
				newAnnouncement.Date = DateTime.Now;
				if (newAnnouncement.Title == null)
				{
					Debug.WriteLine("ENGINN TITILL");
				}
				//setja inn validation
				repository.Add(newAnnouncement);
				UpdateModel(newAnnouncement);
				repository.Save();
				return RedirectToAction("Announcements");
			}
			else
			{
				return RedirectToAction("NoPrivileges", "Home");
			}
		}
    }
}
